PROGRAM OBS_CONVERT

!==========================================================
!doc  THIS PROGRAM READS OBSERVATION DATA THROUGH LAPS INGEST
!doc  AND CONVERTS THE DATA INTO REQUESTED FORMAT, E.G., BUFR
!doc
!doc  HISTORY:
!doc	CREATION:	YUANFU XIE	MAY 2007
!==========================================================

  USE LAPS_PARAMS

  IMPLICIT NONE

  ! LOCAL VARIABLES:
  CHARACTER :: SUFFIX*14,WTFILE*201,RDFILE*201
  INTEGER   :: LENGTH(2),IBFMSG(10000)
  
  ! LAPS CONFIGURATION:
  CALL LAPS_CONFIG

  ! OPEN FILE TO WRITE:
  IF (FORMAT_REQUEST .EQ. 'BUFR') THEN
    SUFFIX = 'bufr'
    CALL GET_DIRECTORY(SUFFIX,WTFILE,LENGTH(1))
    ! OPEN BUFR TABLE:
    CALL GET_DIRECTORY('static',RDFILE,LENGTH(2))
    RDFILE(LENGTH(2)+1:LENGTH(2)+22) = 'prepobs_prep.bufrtable'
    OPEN(UNIT=BFRTBL_CHANNEL,FILE=RDFILE(1:LENGTH(2)+22),STATUS='OLD')

    WRITE(WTFILE(LENGTH(1)+1:LENGTH(1)+14),1) SYSTEM_ASCTIME,'.bufr'
1   FORMAT(A9,A5)
    LENGTH = LENGTH(1)+14

    OPEN(UNIT=OUTPUT_CHANNEL,FILE=WTFILE(1:LENGTH(1)),FORM='UNFORMATTED')
    CALL OPENBF(OUTPUT_CHANNEL,'OUT',BFRTBL_CHANNEL)
  ELSE IF (FORMAT_REQUEST .EQ. 'WRF') THEN
    SUFFIX = 'wrf'
    CALL GET_DIRECTORY(SUFFIX,WTFILE,LENGTH(1))
    WRITE(WTFILE(LENGTH(1)+1:LENGTH(1)+13),2) SYSTEM_ASCTIME,'.wrf'
2   FORMAT(A9,A4)
    LENGTH = LENGTH(1)+13

    OPEN(UNIT=OUTPUT_CHANNEL,FILE=WTFILE(1:LENGTH(1)),FORM='FORMATTED')
  ELSE
    WRITE(6,*) 'MAIN: Unknown data format'
    STOP
  ENDIF

  ! LAPS OBSERVATION DATA INGEST:
  CALL LAPS_INGEST

  ! CLOSE FILE:
  IF (FORMAT_REQUEST .EQ. 'BUFR') THEN
    CLOSE(BFRTBL_CHANNEL)
    ! FORCE FLUSH THE LAST BUFR MESSAGE:
    CALL WRITSA(-OUTPUT_CHANNEL,IBFMSG,LENGTH(1))
  ENDIF
  CLOSE(OUTPUT_CHANNEL)

END PROGRAM OBS_CONVERT
